package com.addzero.addzero_common

import ch.qos.logback.core.util.StatusPrinter.buildStr
import com.addzero.common.consts.sql
import org.babyfish.jimmer.Page
import org.babyfish.jimmer.View
import org.babyfish.jimmer.spring.model.SortUtils
import org.babyfish.jimmer.sql.ast.LikeMode
import org.babyfish.jimmer.sql.kt.KSqlClient
import org.babyfish.jimmer.sql.kt.ast.expression.eq
import org.babyfish.jimmer.sql.kt.ast.expression.like
import org.babyfish.jimmer.sql.kt.ast.query.KConfigurableRootQuery
import org.babyfish.jimmer.sql.kt.ast.query.KMutableRootQuery
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.TestConstructor


data class FilterState(
    val columnKey: String,
    val value: Any,
    val secondaryValue: String? = null,  // 用于范围搜索的第二个值
    val valueList: List<String>? = null, // 用于 IN/NOT IN 操作符
    val operator: SearchOperator = SearchOperator.LIKE,  // 使用枚举类型的操作符
)


data class SortState(
    val columnKey: String,
    val operator: SortOperator = SortOperator.ASC,  // 使用枚举类型的操作符
)

enum class SortOperator {
    ASC, DESC
}


enum class SearchOperator {
    EQ, LIKE
}


inline fun <reified E : Any, reified V : View<E>> queryPage(
    sortStats: List<SortState>,
    filterStates: List<FilterState>,
    ): Page<V> {
    val klass = E::class
    val execute = sql.createQuery<E, V>(klass) {
        baseSpec<E>(filterStates)
        orderBy(SortUtils.toSort(buildStr111k(sortStats)))
        baseSelect<E, V>()
    }.fetchPage(0, 10)
    return execute
}

fun KMutableRootQuery<E>.buildStr111k(sortStats: List<SortState>) {
    TODO("Not yet implemented")
}

inline fun <reified E : Any, reified V : View<E>> KMutableRootQuery<E>.baseSelect(): KConfigurableRootQuery<E, V> =
    select(table.fetch(V::class))

inline fun <reified E : Any> KMutableRootQuery<E>.baseSpec(filterStates: List<FilterState>) {
    filterStates.forEach {
        val columnKey = it.columnKey
        val operator = it.operator
        val value = it.value
        when (operator) {
            SearchOperator.EQ -> {
                where(table.get<Any>(columnKey).eq<Any>(value))
            }

            SearchOperator.LIKE -> {
                where(table.get<String>(columnKey).like(value as String, LikeMode.ANYWHERE))
            }
        }

    }
}


@SpringBootTest
@TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL)
class 测试高级搜索(
    val sql: KSqlClient,
) {


}
